<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

use App\Lib\Auth\UserProfileHelper;
use App\Lib\Secure\CaptchaValidator;

use Auth;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }

    public function toRenderLoginForm()
    {
        return view('auth.loginform');
    }

    /**
    * Override username()
    */
    public function username()
    {
        return 'username';
    }

    /**
    * 验证人机交互逻辑
    */
    protected function validateAIVerifyCode(Request $request)
    {
        if ($request->result_response) {
            $captchaValidator = new CaptchaValidator();
            return $captchaValidator->validateVerifyCode($request->result_response);
        } else {
            return false;
        }
    }

    public function login(Request $request)
    {
        if (config('captcha.enable')) {
            if (!$this->validateAIVerifyCode($request)) {
                return $this->sendFailedValidateVerifyResponse($request);
            }
        }

        $this->validateLogin($request);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);
            return $this->sendLockoutResponse($request);
        }

        if ($this->guard()->attempt(['name' => $request->username, 'password' => $request->password], $request->has('remember')) ||
            $this->guard()->attempt(['mobile' => $request->username, 'password' => $request->password], $request->has('remember')) ||
            $this->guard()->attempt(['email' => $request->username, 'password' => $request->password], $request->has('remember'))) {

            $profileHelper = new UserProfileHelper();
            $profileHelper->initProfile();

            return $this->sendLoginResponse($request);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }

    protected function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user())
            ? response()->json([
                'Success' => false,
                'Message' => '登录失败',
            ]) : response()->json([
                'Success' => true,
                'Message' => '登录成功',
            ]);
    }

    protected function sendLockoutResponse(Request $request)
    {
        return response()->json([
            'Success' => false,
            'Message' => '登录次数过多，用户被锁定一段时间',
        ]);
    }

    protected function sendFailedLoginResponse(Request $request)
    {
        return response()->json([
            'Success' => false,
            'Message' => '用户不存在或者密码不正确',
        ]);
    }

    /**
    * 返回验证失败
    */
    protected function sendFailedValidateVerifyResponse(Request $request)
    {
        return response()->json([
            'Success' => false,
            'Message' => '验证码验证失败',
        ]);
    }

}
